package com.bit.IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class IOTest2 {

    public static void main(String[] args) throws IOException {
        copyFile("d:/test/1234.jpg","d:/test/1.jpg");
        copyFile1("d:/test/1234.jpg","d:/test/2.jpg");
    }
    //文件操作复制文件,有线程安全问题，可能导致资源泄露
    private static void copyFile(String srcPath,String desPath) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(srcPath);
        FileOutputStream fileOutputStream = new FileOutputStream(desPath);
        byte[] buffer = new byte[1024];
        int length = -1;
        while((length=fileInputStream.read(buffer)) != -1){
            fileOutputStream.write(buffer,0,length);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }

    //线程安全
    //将打开文件的操作写到try（）里面，系统就会自动关闭了
    private static void copyFile1(String srcPath,String desPath){
        try (FileInputStream fileInputStream = new FileInputStream(srcPath);
        FileOutputStream fileOutputStream = new FileOutputStream(desPath)){
            int len = -1;
            byte[] buffer = new byte[1024];
            while((len = fileInputStream.read(buffer)) !=-1) {
                fileOutputStream.write(buffer, 0, len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
